package com.zaimokuza.cn.controller;

import com.zaimokuza.cn.entity.PageResult;
import com.zaimokuza.cn.entity.auth.Role;
import com.zaimokuza.cn.entity.auth.UserRoleRelation;
import com.zaimokuza.cn.entity.response.ResponseFormat;
import com.zaimokuza.cn.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zaimokuza
 */
@Api(tags = "角色相关")
@ResponseFormat
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @ApiOperation(value = "添加角色", notes = "添加角色")
    @PostMapping("/add")
    public void addRole(@Validated @RequestBody Role role) {
        roleService.addRole(role);
    }

    @ApiOperation(value = "更新角色", notes = "根据角色ID更新角色名称")
    @PutMapping("/update")
    public void updateRole(@Validated @RequestBody Role role) {
        roleService.updateRoleNameById(role);
    }

    @ApiOperation(value = "更新用户角色关联信息", notes = "更新用户角色关联信息")
    @PutMapping("/relation/update")
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRoleRelations(@Validated @RequestBody UserRoleRelation relations) {
        roleService.updateUserRoleRelations(relations);
    }

    @ApiOperation(value = "删除角色", notes = "根据角色ID删除角色")
    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(@RequestParam @ApiParam("角色ID") String id) {
        roleService.deleteRole(id);
    }

    @ApiOperation(value = "查询角色树", notes = "查询角色树")
    @GetMapping("/tree")
    public List<Role> getRoleTree() {
        return roleService.getRoleTree();
    }

    @ApiOperation(value = "查询用户ID拥有的角色信息", notes = "查询用户ID拥有的角色信息")
    @GetMapping("/user")
    ArrayList<String> getUserRole(@RequestParam @ApiParam("用户ID") String userId) {
        return roleService.getRoleIdListByUserId(userId);
    }

    @ApiOperation(value = "查询角色分页列表", notes = "查询角色分页列表")
    @GetMapping("/page")
    public PageResult<Role> getRolePage(@RequestParam(required = false) @ApiParam("角色名称") String name,
                                        @RequestParam(defaultValue = "1") @ApiParam("当前页") Integer page,
                                        @RequestParam(defaultValue = "10") @ApiParam("每页条数") Integer size) {
        return roleService.getRolePage(name, page, size);
    }

}
